package MyBlockingQueue;

public class MyArrayBlockingQueue {
    String[] arr;
    int size = 0;
    int head = 0;
    int tail = 0;


    //默认数组大小为10
    public MyArrayBlockingQueue(){
        this.arr = new String[10];
    }

    //自定义数组大小
    public MyArrayBlockingQueue(int n){
        this.arr = new String[n];
    }

    //将数据放入到数组容器中
    public void put(String data) throws InterruptedException {
        synchronized (this){
            while (size >= arr.length){
                this.notifyAll();
                this.wait();
            }
            String putData = Thread.currentThread().getName() + "存放了 --> " +data;
            arr[tail] = putData;
            System.out.println(putData);
            Thread.sleep(1000);
            tail++;
            if (tail >= arr.length){
                tail = 0;
            }
            size++;
            this.notifyAll();
            this.wait();
        }
    }

    //将数据取出
    public void take() throws InterruptedException {
        synchronized (this){
            while (size == 0){
                this.notifyAll();
                this.wait();
            }
            String ret = arr[head];
            System.out.println(Thread.currentThread().getName() + "成功取出了 ==>  :"+ret);
            Thread.sleep(1000);
            head++;
            if (head >= arr.length){
                head = 0;
            }
            size--;
            this.notify();
            this.wait();
        }
    }








}
